import { store } from '@/store';
import watermark from '@/utils/watermark';
import axios from "@/axios";
import { ElMessage } from "element-plus";
import { defineStore } from 'pinia';
import { useRouterStore } from '@/store/modules/router';
import router from '@/router';

interface UserState {
    userInfo: any | null;
    token: string | undefined;
    sys: any | null;
    currentSystemName: String | undefined;
    currentSystemCode: String | undefined;
    needCaptcha: boolean | undefined;
}

export const useUserStore = defineStore({
    id: 'app-user',
    state: (): UserState => ({
        //用户信息
        userInfo: null,
        //token
        token: undefined,
        //系统信息
        sys: null,
        //当前系统名称
        currentSystemName: undefined,
        //当前系统代码
        currentSystemCode: undefined,
        //需要验证码
        needCaptcha: undefined,
    }),
    getters: {
        getUser(): any {
            return this.userInfo || JSON.parse(localStorage.getItem("userInfo") || '{}') || {};
        },
        getSys(): any {
            return this.sys || JSON.parse(localStorage.getItem("sys") || '{}') || {};
        },
        getCurrentSystemName(): string {
            // @ts-ignore
            return this.currentSystemName || JSON.parse(localStorage.getItem("currentSystem") || '{}').name || window.WEB_CONFIG.xtmc || ''
        },
        getCurrentSystemCode(): string {
            // @ts-ignore
            return this.currentSystemCode || JSON.parse(localStorage.getItem("currentSystem") || '{}').code || window.WEB_CONFIG.cdRoot || ''
        },
        getToken(): string {
            // @ts-ignore
            return this.token || localStorage.getItem("token") || ''
        },
        getNeedCaptcha(): boolean {
            // @ts-ignore
            return this.needCaptcha || localStorage.getItem("needCaptcha")==="true" || false
        }
    },
    actions: {

        /**
         * 设置用户信息
         * @param userInfo
         */
        setUser(userInfo: any | null) {
            this.userInfo = userInfo;
            if (userInfo) {
                localStorage.setItem("userInfo", JSON.stringify(userInfo))
                watermark.set(userInfo.yhxm + "," + userInfo.yhdm);
            } else {
                localStorage.removeItem("userInfo")
                watermark.set("临时用户");
            }
        },

        /**
         * 设置系统信息
         * @param sys
         */
        setSys(sys: any) {
            this.sys = sys;
            if (sys) {
                localStorage.setItem("sys", JSON.stringify(sys))
            }
            else {
                localStorage.removeItem("sys")
            }
        },

        /**
         * 设置token
         * @param token
         */
        setToken(token: string | undefined) {
            this.token = token
            if (token)
                localStorage.setItem("token", token)
            else {
                localStorage.removeItem("token")
            }
        },

        /**
         * 设置needCaptcha
         * @param needCaptcha
         */
        setNeedCaptcha(needCaptcha: boolean | undefined) {
            this.needCaptcha = needCaptcha
            // @ts-ignore
            localStorage.setItem("needCaptcha", needCaptcha)
        },
        /**
         * 设置当前系统名称
         * @param name
         */
        setCurrentSystemName(name: string | undefined) {
            this.currentSystemName = name
            if (name) {
                localStorage.setItem("currentSystemName", name)
            }
            else {
                localStorage.removeItem("currentSystemName")
            }
        },

        /**
         * 设置当前系统代码
         * @param code
         */
        setCurrentSystemCode(code: string | undefined) {
            this.currentSystemCode = code
            if (code)
                localStorage.setItem("currentSystemCode", code)
            else {
                localStorage.removeItem("currentSystemCode")
            }

        },

        /**
         * 登录
         * @param params
         */
        async login(params: any) {
            await axios.post(params, { ctdy: false })
                .then(async (response: any) => {
                    if (response.status) {
                        this.saveUserInfo(response.data)
                        ElMessage.success("登陆成功");
                        //登录成功设置为不需要验证码
                        this.setNeedCaptcha(false);
                        await useRouterStore().setRouter()
                        router.push("/")
                    } else {
                        //登录失败，在会话中存储失败标记，要进行验证码校验
                        this.setNeedCaptcha(true);
                        ElMessage.error(response.msg);
                    }
                }).catch((error: any) => {
                    //登录失败，在会话中存储失败标记，要进行验证码校验
                    this.setNeedCaptcha(true);
                });

        },

        saveUserInfo(data: any) {
            this.setSys(data.sys)
            this.setUser(data.user)
            this.setToken(data.sys.token)
        },

        /**
         * 登出
         */
        logout() {
            axios.post({
                sjdx: {
                    dxdm: 'SYS_QX_YHXX_MRDL'
                },
                sys: {
                    cllx: 'yhtc'
                }
            }, { ctdy: false }).then((req: any) => {
                if (req.status) {
                    ElMessage.success(req.msg)
                    router.push('/login')
                    //将当前系统代码返回回去
                    this.setToken(undefined)
                    this.setSys(null)
                    this.setCurrentSystemName(undefined)
                    this.setCurrentSystemCode(undefined)
                    this.setUser(null)
                } else {
                    ElMessage.warning(req.msg)
                }
            })

        }
    },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
    return useUserStore(store);
}
